import Taro,{Component} from "@tarojs/taro"
import styles from './index.module.scss'
import { View, Image, Input, Button, Canvas, Checkbox, Label, Picker } from "@tarojs/components"
import {connect} from '@tarojs/redux'
import SIGN_POSITIVE from '@/assets/img/sign_positive.png'
import SIGN_NEGATIVE from '@/assets/img/sign_negative.png'
import SIGN_WARN from '@/assets/img/sign_warn.png'
import { checkInfo, updateCard, getProtocolBySign, getLessonList, getBizTokenByFace, getAuthByWechat } from '@/api/index'
import { toggleSign, setInfo } from '@/actions/user'
import { setUrl } from '@/actions/web'
import { AtActionSheet, AtActionSheetItem, AtIcon } from "taro-ui"
import { filter, dialog } from '@/util/index'
import { isCardID } from '@/assets/js/valid'
import ServiceOnline from '@/components/ServiceOnline'
import {PDF_URL} from '@/api/config'

@connect(({user}) => ({
  info: user.info
}), dispatch => ({
  toggleSign: (data) => dispatch(toggleSign(data)),
  setInfo: (data) => dispatch(setInfo(data)),
  setUrl: (data) => dispatch(setUrl(data)),
}))
class Home extends Component {

  config = {
    navigationBarTitleText: '实名认证'
  }

  state = {
    positiveImg: SIGN_POSITIVE,
    negativeImg: SIGN_NEGATIVE,
    orderidFront: '',
    name: '',
    idCard: '',
    bankCard: '',
    lesson: '',
    lessonLabel: '',
    isOpened: false,
    type: 'POSITIVE',
    imageSize: {
      imageWidth: '',
      imageHeight: ''
    },
    checked: true,
    lessonList: [],
    btnDisabled: false,
    faceFlag: false
  }

  constructor() {
    super(...arguments)
    this.count = 1
  }

  componentWillMount = () => {
    this.wxLogin()
    this.getList()
  }

  getList = async () => {
    try {
      const { data } = await getLessonList()
      let arr = data.dataList ? [{dictValue: '', dictLabel: '无'}, ...data.dataList] : [{dictValue: '', dictLabel: '无'}, ...data]
      this.setState({lessonList: arr, faceFlag: data.falg ? data.falg: false})
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  wxLogin = () => {
    Taro.login({
      success: (res) => {
        if (res.code) {
          this.getAuthByWechat(res.code)
        } else {
          Taro.showToast({title: '登录失败！' + res.errMsg, icon: 'none'})
        }
      },
      fail: (e) => {
        Taro.showToast({title: '微信授权登录login失败:' + e.errMsg, icon: 'none'})
      }
    })
  }

  async getAuthByWechat(code) {
    try {
      const { info, setInfo } = this.props
      const { data } = await getAuthByWechat({code, mobile: info.mobile})
      setInfo({...data})
    } catch (e) {
      console.log('getAuthByWechat:', e.message)
    }
  }

  chooseImageByType = (type) => {
    this.setState({type, isOpened: true})
  }

  chooseImage = async (chooseType) => {
    try{
      const { type } = this.state
      const { tempFilePaths, tempFiles } = await Taro.chooseImage({sourceType: [chooseType], count: 1})
      Taro.showLoading({title: '图片上传ing...', mask: true})
      // let result = await this.getCanvasImg(tempFilePaths[0])
      const res = await Taro.getFileSystemManager().readFileSync(tempFilePaths[0], 'base64')
      Taro.hideLoading()
      let base64 = 'data:image/jpeg;base64,' + res
      let cardImg = type === 'POSITIVE' ? 'positiveImg': 'negativeImg'
      this.setState({[cardImg]: base64, isOpened: false}, () => {
        const { positiveImg, negativeImg } = this.state
        if (positiveImg !== SIGN_POSITIVE && negativeImg !== SIGN_NEGATIVE) {
          this.updateCard()
        }
      })
    } catch(e) {
      console.log(e)
      this.setState({isOpened: false})
    }
  }

  //压缩并获取图片，这里用了递归的方法来解决canvas的draw方法延时的问题
  getCanvasImg = (tempFilePath) => {
    var promise = new Promise((resolve, reject) => {
      var that = this;
      Taro.getImageInfo({
        src: tempFilePath, //图片的路径，可以是相对路径，临时文件路径，存储文件路径，网络图片路径,
        success: res => {
          console.log(res)
          // util.imageUtil  用语计算长宽比
          var imageSize = filter.computedImgSize(res);
          console.log(imageSize)
          that.setState({
            imageSize: imageSize
          })
          const ctx = Taro.createCanvasContext('canvas');
          ctx.drawImage(tempFilePath, 0, 0, imageSize.imageWidth, imageSize.imageHeight);
          ctx.draw(false, function () {
            Taro.canvasToTempFilePath({
              canvasId: 'canvas',
              success: function success(res) {
                resolve(res.tempFilePath)
              },
              fail: function (e) {
                reject(new Error(e))
              }
            });
          });
        },
        fail: () => {},
        complete: () => {}
      });
    })
    return promise
  }

  updateCard = async () => {
    const { positiveImg, negativeImg } = this.state
    try {
      Taro.showLoading({mask: true, title: '校验身份中.'})
      const { data } = await updateCard({positiveIDPhoto: positiveImg, negativeIDPhoto: negativeImg})
      Taro.hideLoading()
      this.setState({name: data.realname, idCard: data.idcard, orderidFront: data.orderidFront})
    } catch(e) {
      this.setState({positiveImg: SIGN_POSITIVE, negativeImg: SIGN_NEGATIVE})
      Taro.showToast({title: e.message, icon: 'none', duration: 4000})
    }
  }

  validateArgs = () => {
    const { name, idCard, bankCard, positiveImg, negativeImg, checked, lesson } = this.state
    if (positiveImg === SIGN_POSITIVE || negativeImg === SIGN_NEGATIVE) {
      Taro.showToast({title: '未上传身份证照片！', icon: 'none'})
      return false
    }
    if (!name) {
      Taro.showToast({title: '未输入姓名！', icon: 'none'})
      return false
    }
    if (!idCard) {
      Taro.showToast({title: '未输入身份证！', icon: 'none'})
      return false
    }
    if (!isCardID(idCard)) {
      Taro.showToast({title: '请输入正确的身份证', icon: 'none'})
      return false
    }
    // if (!bankCard) {
    //   Taro.showToast({title: '未输入银行卡号！', icon: 'none'})
    //   return false
    // }
    if (!checked) {
      Taro.showToast({title: '未勾选协议！', icon: 'none'})
      return false
    }
    return true
  }

  confirm = async (faceRecognitionStatus) => {
    const { name, idCard, bankCard, positiveImg, negativeImg, lesson, orderidFront } = this.state
    const { toggleSign, setInfo, info, setUrl } = this.props
    const { mobile, openid, nickName, gender, city, merchantId } = info
    try {
      Taro.showLoading({mask: true, title: '信息验证中.'})
      const { data } = await checkInfo({idNo: idCard, name, loginAccount: mobile, cardNo: bankCard, positiveIDPhoto: positiveImg, negativeIDPhoto: negativeImg, openid, nickName, gender, city, lessonNo: lesson, orderidFront, faceRecognitionStatus, merchantId})
      Taro.hideLoading()
      toggleSign(true)
      setInfo({idCard, name})
      if (lesson) {
        Taro.switchTab({url: '/pages/taskSquare/index', success: () => {
          Taro.showModal({
            title: '提示',
            content: '您是否现在进入学习课程页面，观看视频学习课程。',
            cancelText: '返回',
            confirmText: '立即前往',
            showCancel: true,
            success: function(res) {
              if (res.confirm) {
                setUrl(data.videoUrl.url)
                Taro.navigateTo({url: '/pages/web/index?title=课程培训&redirectUrl=/pages/taskSquare/index'})
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }})
      } else {
        Taro.switchTab({url: '/pages/taskSquare/index'})
      }
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  goProtocol = async() => {
    try {
      Taro.showLoading({mask: true, title: '文件打开中.'})
      const { data, msg } = await getProtocolBySign()
      this.checkSystemInfo(data)
    } catch (e) {
      Taro.hideLoading()
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  checkSystemInfo = (data) => {
    let _this = this
    wx.getSystemInfo({
      success (res) {
        if (res.system.indexOf('iOS') != -1) {
          _this.props.setUrl(data)
        } else {
          _this.props.setUrl(PDF_URL + data)
        }
        Taro.hideLoading()
        Taro.navigateTo({url: '/pages/web/index?title=' + '数字经济合作伙伴协议'})
      }
    })
  }

  goFace = () => {
    if (!this.validateArgs()) return
    const { idCard, name } = this.state
    getBizTokenByFace({IdCard: idCard, UserName: name}).then(({data}) => {
      this.getFaceApi(data.Response.BizToken)
    }).catch((e) => {
      dialog.toast({title: e.message})
    })
  }

  throttleBtn = () => {
    wx.showLoading({
      title: '加载中',
    })

    setTimeout(function () {
      wx.hideLoading()
    }, 3000)
    this.setState({btnDisabled: true}, () => {
      this.goFace()
      this.setState({btnDisabled: false})
    })
  }

  getFaceApi(bizToken) {
    let _this = this
    wx.startInteractiveVideo({
      data: {
        BizToken: bizToken // BizToken
      },
      success: (res) => { // 验证成功后触发
        // res 包含验证成功的token, 这里需要加500ms延时，防止iOS下不执行后面的逻辑
        setTimeout(() => {
        // 验证成功后，拿到token后的逻辑处理，具体以客户自身逻辑为准
          _this.confirm(1)
        }, 500);
      },
      fail: (err) => { // 验证失败时触发
        // err 包含错误码，错误信息，弹窗提示错误
        setTimeout(() => {
          Taro.showModal({
            title: "提示",
            content: err.ErrorMsg,
            showCancel: true,
            cancelText: '返回',
            confirmText: _this.count > 3 ? '跳过人脸' : '重新认证',
            success: (res) => {
              if (res.confirm) {
                if (_this.count > 3) {
                  _this.confirm(0)
                } else {
                  _this.count += 1
                  _this.goFace()
                }
              } else if (res.cancel) {
                console.log('用户点击取消')
                Taro.reLaunch({url: '/pages/sign/index'})
              }
            }
          })
        }, 500);
      }
    });
  }

  /**
   * @description 提示上传身份证图片，只有diabled属性才能使用
   */
  dialogToast = () => {
    const { positiveImg, negativeImg } = this.state
    if (positiveImg === SIGN_POSITIVE || negativeImg === SIGN_NEGATIVE) {
      Taro.showToast({title: '请上传身份证图片', icon: 'none'})
    }
  }

  callPhone = (phone) => {
    Taro.makePhoneCall({phoneNumber: phone})
  }

  handlerSelect = (e) => {
    let lessonLabel = this.state.lessonList[e.detail.value].dictLabel
    let lesson = this.state.lessonList[e.detail.value].dictValue
    this.setState({lesson, lessonLabel})
  }

  goPrvacy = () => {
    const { setUrl } = this.props
    wx.getSystemInfo({
      success(res) {
        if (res.system.indexOf('iOS') != -1) {
          setUrl('https://tcollect.cocogc.cn/profile/document/%E7%A1%AE%E8%AE%A4%E7%89%88%E3%80%8A%E9%9A%90%E7%A7%81%E6%94%BF%E7%AD%96%E3%80%8B-%20%E6%A4%B0%E4%BA%91%E4%BC%97%E5%8C%85_20201030164720(1).pdf')
        } else {
          setUrl(PDF_URL + 'https://tcollect.cocogc.cn/profile/document/%E7%A1%AE%E8%AE%A4%E7%89%88%E3%80%8A%E9%9A%90%E7%A7%81%E6%94%BF%E7%AD%96%E3%80%8B-%20%E6%A4%B0%E4%BA%91%E4%BC%97%E5%8C%85_20201030164720(1).pdf')
        }
        Taro.navigateTo({url: '/pages/web/index?title=' + '隐私政策'})
      }
    })
  }

  render () {
    const { negativeImg, positiveImg, name, idCard, bankCard, isOpened, lesson, lessonList, lessonLabel, btnDisabled, faceFlag } = this.state
    return (
      <View className={styles.wrapper}>
        <View className={styles.containerWrapper}>
          <View className={styles.cardWrapper}>
            <View className={styles.cardTitle}>请上传您的身份证照片：</View>
            <View className={styles.cardContainer}>
              <View className={styles.card}>
                <Image src={positiveImg} className={styles.cardImg} onClick={() => this.chooseImageByType('POSITIVE')}></Image>
              </View>
              <View className={styles.card}>
                <Image src={negativeImg} className={styles.cardImg} onClick={() => this.chooseImageByType('NEGATIVE')}></Image>
              </View>
            </View>
          </View>
          <View className={styles.inputWrapper}>
            <View className={styles.inputItem}>
              <View className={styles.inputLabel}>姓名</View>
              <Input
                placeholder={'请输入本人真实姓名'}
                placeholderStyle={'color: #CCCCCC;'}
                className={styles.input}
                value={name}
                onBlur={(e) => {wx.hideKeyboard({complete: res => {console.log('hideKeyboard res', res)}});this.setState({name: e.detail.value})}}
                onInput={(e) => this.setState({name: e.detail.value})}></Input>
            </View>
            <View className={styles.inputItem}>
              <View className={styles.inputLabel}>身份证号码</View>
              <Input
                placeholder={'请输入二代身份证号码'}
                placeholderStyle={'color: #CCCCCC;'}
                className={styles.input}
                value={idCard}
                onBlur={(e) => {wx.hideKeyboard({complete: res => {console.log('hideKeyboard res', res)}});this.setState({idCard: e.detail.value})}}
                onInput={(e) => this.setState({idCard: e.detail.value})}></Input>
            </View>
            {/* <View className={styles.inputItem}>
              <View className={styles.inputLabel}>银行卡号</View>
              <Input type={'number'} placeholder={'请输入本人银行收款储蓄卡卡号'} placeholderStyle={'color: #CCCCCC;'} className={styles.input} value={bankCard} onInput={(e) => this.setState({bankCard: e.detail.value})}></Input>
            </View> */}
            <View className={styles.inputItem}>
              <View className={styles.inputLabel}>培训课程</View>
              <Picker mode="selector" range={lessonList} rangeKey="dictLabel" onChange={this.handlerSelect}>
                <Input placeholder={'请选择需要学习的课程'} placeholderStyle={'color: #CCCCCC;'} className={styles.input} value={lessonLabel} disabled></Input>
                <AtIcon value='chevron-right' size='22' color='#CCCCCC' className={styles.icon}></AtIcon>
              </Picker>
            </View>
          </View>
          <View className={styles.warnWrapper}>
            <Image src={SIGN_WARN} className={styles.warnIcon}></Image>
            <View className={styles.warn}>选择对应培训课程通过实名认证后，系统将会给您匹配对应的学习视频（非必填项）</View>
          </View>
          <View className={styles.protocolWrapper}>
            <Label className={styles.label} onClick={e => this.setState(pre => ({checked: !pre.checked, btnDisabled: !pre.btnDisabled}))}>
              <Checkbox className={styles.checkbox} checked={this.checked}></Checkbox>我已阅读并同意
            </Label>
            <Text className={styles.protocol} onClick={this.goProtocol}>《数字经济合作伙伴协议》</Text>及
            <Text className={styles.protocol} onClick={this.goPrvacy}>《隐私政策》</Text>
          </View>
          <Button className={styles.confirm} onClick={() => faceFlag ? this.throttleBtn(): this.confirm(0)} disabled={btnDisabled}>提交</Button>
        </View>
        <View className={styles.footerWrapper}>
          联系客服： <Text className={styles.mobile} onClick={() => this.callPhone("4000096337")}>400-009-6337</Text>
        </View>
        <View className={styles.serviceOnline}>
          <ServiceOnline/>
        </View>
        <AtActionSheet isOpened={isOpened} onClose={() => this.setState({isOpened: false})}>
          <AtActionSheetItem onClick={() => this.chooseImage('camera')}>
            拍照
          </AtActionSheetItem>
          <AtActionSheetItem onClick={() => this.chooseImage('album')}>
            上传图片
          </AtActionSheetItem>
        </AtActionSheet>
        <Canvas style={`width:${imageSize.imageWidth}px;height:${imageSize.imageHeight}px;position: absolute;left:-1000px;top:-1000px;`} canvasId='canvas' />
      </View>
    )
  }
}

export default Home
